package com.lehecai.core.lottery.fetcher.lotterydraw.impl.worker;

import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDraw;
import com.lehecai.core.util.CharsetConstant;
import com.lehecai.core.util.CoreFetcherUtils;
import org.apache.commons.lang.StringUtils;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.util.NodeList;

/**
 * Created by zhangzq on 14-8-8.
 */
public class LotteryDrawFetch543Worker163 extends FrequentLotteryDrawFetchWorker163 {

    public LotteryDrawFetch543Worker163(LotteryType lotteryType) {
        super(lotteryType);
    }

    public LotteryDraw fetchResultDetail(String phase) {
        String lotteryPhase;
        String timeDraw = "";
        String result = "";

        LotteryType lotteryType = this.getLotteryType();
        String url = this.getResultDetailUrl(phase);
        if (StringUtils.isEmpty(url) ) {
            logger.error("未获取得到详情的url信息");
            return null;
        }
        String data = CoreFetcherUtils.URLGet(url, null, CharsetConstant.CHARSET_GBK);
        if (data == null || data.indexOf("404 Not Found") > 0) {
            logger.error("data is null or 404 Not Found");
            return null;
        }
        Parser parser = Parser.createParser(data, CharsetConstant.CHARSET_GBK);
        Parser phaseParser = Parser.createParser(data, CharsetConstant.CHARSET_GBK);
        Parser resultParser = Parser.createParser(data, CharsetConstant.CHARSET_GBK);
        //获取开奖时间
        NodeList timeDrawNodeList;
        try {
            NodeFilter cssFilter = new HasAttributeFilter("id", "time");
            timeDrawNodeList = parser.extractAllNodesThatMatch(cssFilter);
            if (timeDrawNodeList != null && timeDrawNodeList.size() > 0) {
                timeDraw = timeDrawNodeList.elementAt(0).toPlainTextString();
            }
        } catch (Exception e) {
            logger.error("数据解析开奖时间错误");
            logger.error(e.getMessage(), e);
            return null;
        }
        //彩期获取
        NodeList phaseNodeList;
        try {
            NodeFilter spanFilter = new HasAttributeFilter("id", "date_no");
            phaseNodeList = phaseParser.extractAllNodesThatMatch(spanFilter);
            if (phaseNodeList != null && phaseNodeList.size() > 0) {
                lotteryPhase = phaseNodeList.elementAt(0).toPlainTextString();
                if (StringUtils.isEmpty(lotteryPhase)) {
                    logger.error("页面抓取的彩期号({})不存在,返回null ", lotteryPhase);
                    return null;
                }
                lotteryPhase = lotteryPhase.replace("期", "").trim();
                //指定彩期为null，抓取列表页面的彩期数据
                if (StringUtils.isEmpty(phase)) {
                    phase = lotteryPhase;
                //当前期可写入详细url，以便抓取对应的详细信息
                } else {
                    if (lotteryPhase.equals(phase)) {
                        phase = lotteryPhase;
                    } else {
                        logger.error("指定抓取的彩期号({})与页面抓取的彩期号({})不一致,返回null ", phase, lotteryPhase);
                        return null;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("解析彩期错误");
            logger.error(e.getMessage(), e);
            return null;
        }
        //获取开奖结果
        NodeList resultNodeList;
        try {
            NodeFilter spanFilter = new HasAttributeFilter("id", "zj_area");
            resultNodeList = resultParser.extractAllNodesThatMatch(spanFilter);
            if (resultNodeList != null && resultNodeList.size() > 0) {
                NodeList nodeList = resultNodeList.elementAt(0).getChildren();
                if (nodeList != null && nodeList.size() >= 27) {
                    String[] resultArray = {
                            nodeList.elementAt(7).toPlainTextString(),nodeList.elementAt(8).toPlainTextString(),nodeList.elementAt(9).toPlainTextString(),nodeList.elementAt(10).toPlainTextString(),
                            nodeList.elementAt(11).toPlainTextString(),nodeList.elementAt(12).toPlainTextString(),nodeList.elementAt(13).toPlainTextString(),nodeList.elementAt(14).toPlainTextString(),
                            nodeList.elementAt(15).toPlainTextString(),nodeList.elementAt(16).toPlainTextString(),nodeList.elementAt(17).toPlainTextString(),nodeList.elementAt(18).toPlainTextString(),
                            nodeList.elementAt(19).toPlainTextString(),nodeList.elementAt(20).toPlainTextString(),nodeList.elementAt(21).toPlainTextString(),nodeList.elementAt(22).toPlainTextString(),
                            nodeList.elementAt(23).toPlainTextString(),nodeList.elementAt(24).toPlainTextString(),nodeList.elementAt(25).toPlainTextString(),nodeList.elementAt(26).toPlainTextString(),
                            nodeList.elementAt(3).toPlainTextString()
                    };
                    if (resultArray != null && resultArray.length == 21 && !resultArray[1].isEmpty()) {
                        result = CoreFetcherUtils.mergeStringArray(resultArray, ",");
                    } else {
                        logger.error("未抓取到相应的开奖结果");
                        return null;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("解析开奖结果错误");
            logger.error(e.getMessage(), e);
            return null;
        }
        LotteryDraw lotteryDraw = new LotteryDraw();
        lotteryDraw.setLotteryType(lotteryType);
        lotteryDraw.setPhase(phase);
        lotteryDraw.setTimeDraw(timeDraw);
        lotteryDraw.setResult(result);
        if (StringUtils.isEmpty(lotteryDraw.getPhase())) {
            logger.error("未抓取到相应的开奖结果");
            return null;
        }
        return lotteryDraw;
    }

    @Override
    protected String getResultDetailUrl(String phase) {
        String detailUrl;
        if (StringUtils.isEmpty(phase)) {
            detailUrl = historyUrlMap.get(this.getLotteryType());
        } else {
            detailUrl = historyUrlMap.get(this.getLotteryType()) + phase + ".html";
        }
        return detailUrl;
    }

    @Override
    public String getResultAttribute() {
        return "";
    }

    public static void main(String[] args) {
        String phase = null;
        // 好运11选5: HLJ11X5 广东快乐十分: GDKL10  快3: JLK3  快乐8: BJKL8
        LotteryDrawFetch543Worker163 lotteryDrawFetch543Worker163 = new LotteryDrawFetch543Worker163(LotteryType.BJKL8);
        LotteryDraw resultListObj = lotteryDrawFetch543Worker163.fetchResult(phase);
        LotteryDraw resultDetailObj = lotteryDrawFetch543Worker163.fetchResultDetail(phase);
    }

}
